<template>
  <view class="time-record-page">
    <!-- Custom Navigation Bar -->
    <uni-segmented-control class="segmented-control" :current="recordForm.mode" :values="['手动记录', '计时器']" :style-type="styleType"
      active-color="rgb(40, 167, 69)" @clickItem="onClickItem" />
    <!-- <uni-segmented-control :items="['手动记录', '计时器']" :value="recordForm.mode" @change="setMode"
    class="segmented-control" /> -->
    <!-- Main Content -->
    <scroll-view class="main-content" scroll-y>


      <!-- Activity Category -->
      <view class="form-item">
          <text class="form-label">活动分类</text>
          <uni-data-select v-model="categoryIndex" :localdata="categoryOptions"
            @change="selectCategory"></uni-data-select>
        </view>

      <!-- Manual Mode -->
      <view v-if="recordForm.mode === 0" class="manual-mode-section">
        
        <!-- Start Time -->
        <view class="form-item">
          <text class="form-label">开始时间</text>
          <view class="datetime-row">
            <uni-datetime-picker type="datetime" v-model="recordForm.startDate" @change="setStartDate" />

          </view>
        </view>

        <!-- End Time -->
        <view class="form-item">
          <text class="form-label">结束时间</text>
          <view class="datetime-row">
            <uni-datetime-picker type="datetime" v-model="recordForm.endDate" @change="setEndDate" />

          </view>
        </view>

        <!-- Duration Display -->
        <view class="form-item">
          <text class="form-label">时长 (可选, 自动计算)</text>
          <input class="form-input" :value="calculateDuration()" placeholder="例如: 1h 30m" disabled />
        </view>

        <!-- Notes -->
        <view class="form-item">
          <text class="form-label">备注 (可选)</text>
          <textarea class="form-textarea" v-model="recordForm.notes" placeholder="记录一些细节..." maxlength="200" />
        </view>

        <!-- Save Button -->
        <button class="save-button" @tap="saveRecord">保存记录</button>
      </view>

      <!-- Timer Mode -->
      <view v-if="recordForm.mode === 1" class="timer-mode-section">

        <!-- Timer Display -->
        <view class="timer-display">
          <text class="timer-time">{{ formatTime(currentTime) }}</text>
        </view>

        <!-- Timer Controls -->
        <view class="timer-controls">
          <button class="control-button start" @tap="startTimer"
            v-if="timerStatus === 'stopped' || timerStatus === 'paused'">
            <text class="control-icon fas fa-play"></text>
            <text class="control-text">开始</text>
          </button>
          <button class="control-button pause" @tap="pauseTimer" v-if="timerStatus === 'running'">
            <text class="control-icon fas fa-pause"></text>
            <text class="control-text">暂停</text>
          </button>
        </view>

        <!-- Notes -->
        <view class="form-item notes-after-timer">
          <text class="form-label">备注 (可选, 计时结束后填写)</text>
          <textarea class="form-textarea" v-model="recordForm.notes" placeholder="计时结束后添加备注..." maxlength="200" />
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import uniNavBar from '@dcloudio/uni-ui/lib/uni-nav-bar/uni-nav-bar.vue'

export default {
  components: {
    uniNavBar,
  },
  data() {
    return {
      segmentedItems: [
        { label: '手动记录', value: 'manual' },
        { label: '计时器', value: 'timer' },
      ],
      recordForm: {
        name: '', // Not used in this page based on prototype
        category: 'work',
        description: '', // Not used in this page based on prototype
        mode: 0, // 'manual' or 'timer'
        startDate: '',
        startTime: '',
        endDate: '',
        endTime: '',
        targetDuration: '', // Not used in this page based on prototype
        priority: 'medium', // Not used in this page based on prototype
        tags: [], // Not used in this page based on prototype
        location: '', // Not used in this page based on prototype
        mood: '', // Not used in this page based on prototype
        energyLevel: 5, // Not used in this page based on prototype
        notes: '',
        satisfaction: 0, // Not used in this page based on prototype
      },
      timerStatus: 'stopped', // stopped, running, paused
      currentTime: 0, // seconds
      timerInterval: null,
      categoryOptions: [
        { value: 'work', text: '工作 - 项目A' },
        { value: 'study', text: '学习 - 专业课程' },
        { value: 'exercise', text: '运动 - 健身房' },
        { value: 'hobby', text: '爱好 - 绘画' },
        { value: 'social', text: '社交 - 朋友聚会' },
        { value: 'rest', text: '休息 - 午休' },
        { value: 'entertainment', text: '娱乐 - 看电影' },
        { value: 'household', text: '家务 - 清洁' },
        { value: 'other', text: '其他 - 杂项' },
      ],
      categoryIndex: 0,
    }
  },
  computed: {
    selectedCategoryLabel() {
      return this.categoryOptions[this.categoryIndex].label
    },
  },
  mounted() {
    this.initializeForm()
  },
  beforeDestroy() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval)
    }
  },
  methods: {
    initializeForm() {
      const now = new Date()
      this.recordForm.startDate = now.toISOString().split('T')[0]
      this.recordForm.startTime = now.toTimeString().split(' ')[0].substring(0, 5)
      this.recordForm.endDate = now.toISOString().split('T')[0]
      this.recordForm.endTime = now.toTimeString().split(' ')[0].substring(0, 5)
      this.categoryIndex = this.categoryOptions.findIndex(c => c.value === this.recordForm.category)
    },
    goBack() {
      if (this.timerStatus === 'running') {
        uni.showModal({
          title: '提示',
          content: '计时器正在运行，确定要离开吗？',
          success: (res) => {
            if (res.confirm) {
              this.stopTimer()
              uni.navigateBack()
            }
          },
        })
      } else {
        uni.navigateBack()
      }
    },
    selectCategory(e) {
      // this.categoryIndex = e.detail.value
      // this.recordForm.category = this.categoryOptions[this.categoryIndex].value
    },
    onClickItem(e) {
      if (this.recordForm.mode !== e.currentIndex) {
        this.recordForm.mode = e.currentIndex
      }
    },

    setStartDate(e) {
      this.recordForm.startDate = e.detail.value
    },
    setStartTime(e) {
      this.recordForm.startTime = e.detail.value
    },
    setEndDate(e) {
      this.recordForm.endDate = e.detail.value
    },
    setEndTime(e) {
      this.recordForm.endTime = e.detail.value
    },
    startTimer() {
      this.timerStatus = 'running'
      this.timerInterval = setInterval(() => {
        this.currentTime++
      }, 1000)
    },
    pauseTimer() {
      this.timerStatus = 'paused'
      if (this.timerInterval) {
        clearInterval(this.timerInterval)
        this.timerInterval = null
      }
    },
    stopTimer() {
      this.timerStatus = 'stopped'
      if (this.timerInterval) {
        clearInterval(this.timerInterval)
        this.timerInterval = null
      }
    },
    resetTimer() {
      this.stopTimer()
      this.currentTime = 0
    },
    formatTime(seconds) {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = seconds % 60

      const formattedHours = hours.toString().padStart(2, '0')
      const formattedMinutes = minutes.toString().padStart(2, '0')
      const formattedSecs = secs.toString().padStart(2, '0')

      return `${formattedHours}:${formattedMinutes}:${formattedSecs}`
    },
    calculateDuration() {
      if (
        !this.recordForm.startDate ||
        !this.recordForm.startTime ||
        !this.recordForm.endDate ||
        !this.recordForm.endTime
      ) {
        return '0h 0m'
      }

      const startDateTime = new Date(
        `${this.recordForm.startDate} ${this.recordForm.startTime}`
      )
      const endDateTime = new Date(
        `${this.recordForm.endDate} ${this.recordForm.endTime}`
      )

      if (endDateTime <= startDateTime) {
        return '0h 0m'
      }

      const diffMs = endDateTime - startDateTime
      const diffMinutes = Math.floor(diffMs / (1000 * 60))
      const hours = Math.floor(diffMinutes / 60)
      const minutes = diffMinutes % 60

      return `${hours}h ${minutes}m`
    },
    saveRecord() {
      if (this.recordForm.mode === 'manual') {
        if (
          !this.recordForm.startDate ||
          !this.recordForm.startTime ||
          !this.recordForm.endDate ||
          !this.recordForm.endTime
        ) {
          uni.showToast({
            title: '请填写完整的开始和结束时间',
            icon: 'none',
          })
          return
        }
        const startDateTime = new Date(
          `${this.recordForm.startDate} ${this.recordForm.startTime}`
        )
        const endDateTime = new Date(
          `${this.recordForm.endDate} ${this.recordForm.endTime}`
        )
        if (endDateTime <= startDateTime) {
          uni.showToast({
            title: '结束时间必须晚于开始时间',
            icon: 'none',
          })
          return
        }
      } else if (this.recordForm.mode === 'timer') {
        if (this.currentTime === 0) {
          uni.showToast({
            title: '计时器未开始或时长为零',
            icon: 'none',
          })
          return
        }
      }

      uni.showToast({
        title: '记录已保存',
        icon: 'success',
      })
      // Here you would typically send the recordForm data to a backend API
      console.log('Record saved:', this.recordForm)
      // uni.navigateBack();
    },
  },
}
</script>

<style lang="scss">
.time-record-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
}

.main-content {
  flex: 1;
  padding: 32rpx; /* 调整整体内边距 */
  box-sizing: border-box;
}

.segmented-control {
  margin-top: 48rpx;
  padding: 0 32rpx;
  margin-bottom: 40rpx; /* 增加分段器与下方内容的间距 */
}


.form-item {
  margin-bottom: 40rpx; /* 增加表单项之间的间距 */

  &:last-of-type {
    margin-bottom: 0;
  }

  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx; /* 增加标签与输入框的间距 */
    display: block;
  }


  .form-input,
  .form-textarea {
    width: 100%;
    padding: 20rpx 25rpx;
    border: 1px solid #dcdcdc; /* 调整边框颜色 */
    border-radius: 12rpx; /* 调整圆角 */
    font-size: 32rpx; /* 统一字体大小 */
    color: #333;
    background-color: #f8f8f8; /* 调整背景色 */
    box-sizing: border-box;
    transition: border-color 0.3s ease, box-shadow 0.3s ease;

    &:focus {
      border-color: #28a745; /* 聚焦时边框颜色 */
      box-shadow: 0 0 0 3rpx rgba(40, 167, 69, 0.2); /* 聚焦时阴影 */
    }
  }

  .form-textarea {
    min-height: 180rpx; /* 增加文本域最小高度 */
    line-height: 1.6; /* 调整行高 */
  }

  .datetime-row {
    display: flex;
    gap: 20rpx;

    .date-picker,
    .time-picker {
      flex: 1;

      .picker-display {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx 25rpx;
        border: 1px solid #dcdcdc; /* 调整边框颜色 */
        border-radius: 12rpx; /* 调整圆角 */
        background-color: #f8f8f8; /* 调整背景色 */

        .picker-text {
          font-size: 32rpx;
          color: #333;
        }

        .picker-icon {
          font-size: 32rpx;
          color: #999;
        }
      }
    }
  }
}

.save-button {
  background-color: #28a745;
  color: #fff;
  // font-size: 36rpx;
  // padding: 25rpx 0;
  // border-radius: 15rpx;
  margin-top: 60rpx;
  margin-bottom: 20rpx;
  width: 100%;
  box-shadow: 0 4px 10px rgba(40, 167, 69, 0.2);
}

.timer-mode-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
  background-color: #fff;
  border-radius: 15rpx;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .timer-display {
    margin-bottom: 60rpx;

    .timer-time {
      font-size: 100rpx;
      font-weight: bold;
      color: #333;
      font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    }
  }

  .timer-controls {
    display: flex;
    justify-content: center;
    gap: 30rpx; /* 调整按钮间距 */

    .control-button {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      padding: 25rpx 50rpx; /* 调整按钮内边距 */
      border-radius: 15rpx;
      font-size: 36rpx;
      color: #fff;
      border: none;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      line-height: 1;

      &.start {
        background-color: #28a745;
        .control-icon {
          font-size: 45rpx;
        }
      }
      &.pause {
        background-color: #ffc107;
        .control-icon {
          font-size: 45rpx;
        }
      }
      &.stop {
        background-color: #dc3545;
        .control-icon {
          font-size: 45rpx;
        }
      }
      &.reset {
        background-color: #6c757d;
        .control-icon {
          font-size: 45rpx;
        }
      }

      .control-icon {
        font-size: 45rpx;
        margin-right: 15rpx;
        margin-bottom: 0;
      }
      .control-text {
        font-size: 38rpx;
      }
    }
  }

  .notes-after-timer {
    width: 100%;
    padding: 0 30rpx;
    box-sizing: border-box;
    margin-top: 60rpx;
  }
}
.tab-section {
  display: flex;
  width: 100%;
  background-color: #f0f0f0;
  border-radius: 15rpx;
  overflow: hidden;
  margin-bottom: 40rpx;
  height: 80rpx; /* 调整分段器高度 */

  .tab-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 32rpx; /* 调整字体大小 */
    color: #333;
    transition: all 0.3s ease;
    line-height: normal; /* 调整行高 */

    &.active {
      background-color: #e0ffe0; /* 更浅的绿色背景 */
      color: #28a745; /* 绿色字体 */
      font-weight: bold;
    }
  }
}
</style>